<?php

class Router {

  /**
   * array of route
   * @var array
   */
  protected static $_routes = array();

  /**
   * add array of route to listener
   * @param array $routes 
   */
  public static function add(array $routes) {
    foreach ($routes as $route) {
      self::$_routes[] = $route;
    }
  }

  /**
   * boot route should call one.
   *
   */
  public static function boot() {
    Logger::add('route::boot');
  }

  /**
   *
   * @param  string $uri
   * @return array (string $action_name, array $args)
   */
  public static function match($uri) {

    $part = explode('/', trim($uri, '/'));

    $pkg = $part[0];
    $pkg = ucfirst(strtolower($pkg));

    $filename = ROOT_PATH . DIRECTORY_SEPARATOR . 'route.php';
    @require_once $filename;
    Logger::add('load route', $filename);

    foreach (self::$_routes as $route) {
      $pattern = '#' . $route[0] . '#i';
      if (preg_match($pattern, $uri, $match)) {
        $args = array();
        $remain = explode('/', trim(str_replace($match[0], '', $uri), '/'));
        $len = count($remain);
        for ($i = 0; $i < $len; $i+=2) {
          if ($remain[$i]) {
            @$args[$remain[$i]] = $remain[$i + 1];
          }
        }
        $args  = array_merge($args, $match);
        return array($route[1], $args);
      }
    }
    return array('Manage.Admin.NotFound', array());
  }

}